#!/bin/sh
# shellcheck disable=1090,1091

# Shared code between boot/shutdown.
. /usr/lib/init/rc.lib

log "Loading rc.conf settings..."; {
    [ -f /etc/rc.conf ] && . /etc/rc.conf
}

log "Running shutdown pre hooks..."; {
    run_hook pre.shutdown
}

log "Waiting for services to stop..."; {
    sv force-shutdown /var/service/* >/dev/null 2>&1
}

log "Saving random seed..."; {
    random_seed save
}

log "Sending TERM signal to all processes..."; {
    kall 15
    sleep 2
}

log "Sending KILL signal to all processes..."; {
    kall 9
}

log "Unmounting filesystems and disabling swap..."; {
    swapoff -a

    # Skip unmounting pseudo filesystems as they may be
    # needed below for encryption and user shutdown scripts.
    #
    # The '-t' flag is a part of the LSB standard and is
    # supported by busybox, toybox, util-linux, FreeBSD,
    # NetBSD, OpenBSD and others.
    #
    # This flag is unsupported by ubase and I consider this
    # a ubase issue. ubase only supports Linux and this
    # flag is a part of the Linux standard base.
    umount -rat nosysfs,proc,devtmpfs,tmpfs
}

log "Remounting rootfs as read-only"; {
    mount -o remount,ro /
    sync
}

log "Running shutdown post hooks..."; {
    run_hook post.shutdown
}

# Run 'kpow' to signal to the kernel that we want to reboot or
# poweroff the system. These will only run when '$1' contains
# a valid action. When busybox init is used, this code is
# ignored entirely as it handles this itself.
case $1 in
    reboot)   kpow r ;;
    poweroff) kpow p ;;
esac
